package cn.wjdiankong.toutiaovideo;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.KeyStore;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.CRC32;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.content.Context;
import android.util.Base64;
import android.util.Log;
import cn.wjdiankong.levideo.utils.Logger;

public final class ToutiaoUtils {

	public static String getHtmlContent(String url){
		StringBuffer sbHTML;
		BufferedReader br = null;
		try {
			HttpClient hc = getNewHttpClient();
			HttpGet hg = new HttpGet(url);
			HttpResponse hr = hc.execute(hg);
			br = new BufferedReader(new InputStreamReader(hr
					.getEntity().getContent()));
			String line = "";
			sbHTML = new StringBuffer();
			while ((line = br.readLine()) != null) {
				sbHTML.append(line);
			}
			return sbHTML.toString();
		} catch (Exception e) {
			Logger.log("jw", "error:"+Log.getStackTraceString(e));
			return null;
		} finally{
			try {
				br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static String getCRC32Url(String htmlStr){
		try{
			String regEx = "videoid:(.+?),";
			Pattern pat = Pattern.compile(regEx);
			Matcher mat = pat.matcher(htmlStr);
			String videoId = null;
			Logger.log("jw", "isfind:"+mat.find());
			for(int i=1;i<=mat.groupCount();i++){
				videoId = mat.group(i);
			}
			videoId = videoId.substring(1, videoId.length()-1);
			String url = "/video/urls/v/1/toutiao/mp4/"+videoId;
			String r = String.valueOf(Math.random()).substring(2);
			url += "?r="+r;
			CRC32 crc32 = new CRC32();
			crc32.update(url.getBytes());
			String s = (crc32.getValue()&0xffffffff)+"";
			Logger.log("jw", s);
			url = "http://i.snssdk.com"+url+"&s="+s;
			Logger.log("jw", "url:"+url);
			return url;
		}catch(Exception e){
			return null;
		}
	}

	public static String getVideoJsonData(String url){
		ByteArrayOutputStream bos = null;
		try {
			HttpClient hc = getNewHttpClient();
			HttpGet hg = new HttpGet(url);
			HttpResponse hr = hc.execute(hg);
			bos = new ByteArrayOutputStream();
			InputStream is = hr.getEntity().getContent();
			byte[] buffer = new byte[1024];
			int len = -1;
			while ((len=is.read(buffer)) != -1) {
				bos.write(buffer, 0, len);
			}
			return new String(bos.toByteArray());
		} catch (Exception e) {
			Logger.log("error:"+Log.getStackTraceString(e));
			return null;
		} finally{
			try{
				bos.close();
			}catch(Exception e){

			}
		}
	}

	public static String parseJsonGetMainUrl(String jsonStr){
		try{
			JSONObject json = new JSONObject(jsonStr);
			JSONObject dataJ = json.getJSONObject("data");
			JSONObject videoListJ = dataJ.getJSONObject("video_list");
			JSONObject videoJ = videoListJ.getJSONObject("video_1");
			String mainUrlJ = videoJ.getString("main_url");
			return new String(Base64.decode(mainUrlJ, Base64.DEFAULT));
		}catch(Exception e){
			Logger.log("error:"+Log.getStackTraceString(e));
			return null;
		}
	}

	public static String downloadVideo(String url, File videoFile){
		FileOutputStream fos = null;
		try {
			HttpClient hc = getNewHttpClient();
			HttpGet hg = new HttpGet(url);
			HttpResponse hr = hc.execute(hg);
			if(!videoFile.getParentFile().exists()){
				videoFile.getParentFile().mkdirs();
			}
			fos = new FileOutputStream(videoFile);
			InputStream is = hr.getEntity().getContent();
			byte[] buffer = new byte[1024];
			int len = -1;
			while ((len=is.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
			}
			fos.flush();
			Logger.log("download video finish:"+videoFile.getAbsolutePath());
			return videoFile.getAbsolutePath();
		} catch (Exception e) {
			Logger.log("error:"+Log.getStackTraceString(e));
		} finally{
			try{
				fos.close();
			}catch(Exception e){
			}
		}
		return "";
	}

	public static String filterVideoUrl(String url){
		try{
			String regEx = "/group/(.+?)/?iid";
			Pattern pat = Pattern.compile(regEx);
			Matcher mat = pat.matcher(url);
			String groupId = null;
			while(mat.find()){  
				groupId = mat.group();
	        }  
			groupId = groupId.substring(7, groupId.length()-5);
			return "http://www.toutiao.com/a"+groupId;
		}catch(Exception e){
			Logger.log("get iid err:"+Log.getStackTraceString(e));
			return null;
		}
	}
	
	public static void copyFileToAppData(Context ctx){ 
		String videoPath = ctx.getFilesDir()+File.separator+"useguide.mp4";
		File videoFile = new File(videoPath);
		if(videoFile.exists()){
			return;
		}
		InputStream myInput = null;  
		OutputStream myOutput = null;
		try{
			myInput = ctx.getAssets().open("useguide.mp4");
			myOutput = new FileOutputStream(videoFile);
			byte[] buffer = new byte[1024];
			int len = -1;
			while((len=myInput.read(buffer)) != -1){
				myOutput.write(buffer, 0, len); 
			}
		}catch(Exception e){
		}finally{
			try {
				myOutput.flush();
				myInput.close();  
				myOutput.close();
			} catch (Exception e) {
			}  
		}
	} 
	
	public static HttpClient getNewHttpClient() {  
        try {  
            KeyStore trustStore = KeyStore.getInstance(KeyStore  
                    .getDefaultType());  
            trustStore.load(null, null);  
  
            SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);  
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
  
            HttpParams params = new BasicHttpParams();  
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);  
  
            SchemeRegistry registry = new SchemeRegistry();  
            registry.register(new Scheme("http", PlainSocketFactory  
                    .getSocketFactory(), 80));  
            registry.register(new Scheme("https", sf, 443));  
  
            ClientConnectionManager ccm = new ThreadSafeClientConnManager(  
                    params, registry);  
  
            return new DefaultHttpClient(ccm, params);  
        } catch (Exception e) {  
            return new DefaultHttpClient();  
        }  
    }  
	
	
	
}
